package com.mmall.service.impl;

import com.google.common.collect.Lists;
import com.mmall.service.IFileService;
import com.mmall.util.FTPUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Classname FileServiceImpl
 * @Description TODO
 * @Date 2020/8/13 20:21
 * @Created by ccc-j
 * @email ccc-ju@outlook.com
 */
@Service("iFileService")
public class FileServiceImpl implements IFileService {

    private Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    public String upload(MultipartFile file, String path){
        String fileName = file.getOriginalFilename();
        //获取扩展名
        String fileExtensionName = fileName.substring(fileName.lastIndexOf("."));
        String uploadFileName = UUID.randomUUID().toString() + fileExtensionName;
        logger.info("开始上传文件，上传文件的文件名:{}, 上传的路径是:{}, 新文件名:{}", fileName, path, uploadFileName);

        File fileDir = new File(path);
        if(!fileDir.exists()){
            logger.info("传入的文件夹路径{} 不存在,开始进行创建---------------------");
            fileDir.setWritable(true);
            fileDir.mkdirs();
            logger.info("传入的文件夹路径创建完毕！");
        }
        File targetFile = new File(path, uploadFileName);
        try {
            file.transferTo(targetFile);
            //文件上传成功
            FTPUtils.uploadFile(Lists.newArrayList(targetFile));
            //已经上传到FTP服务器

            //上传完之后,删除upload下文件
            targetFile.delete();
        } catch (IOException e) {
            logger.error("上传文件异常", e);
            return null;
        }
        return targetFile.getName();
    }

}
